#
# Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
#
# GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
# Author: Shawn.Tan
# Date: 2025.10.28
#
# History: Initial Version 2025.10.28
#
#
import RandomUtils

from DV.gpgpu.trees.instruction_tree import RV_G_map, RV32_G_map
from base.Sequence import Sequence
from gpgpu.EnvGPGPU import EnvGPGPU
from gpgpu.GenThreadGPGPU import GenThreadGPGPU


# This test intentionally returns to an address that will generate a page
# fault on instruction fetch at the end of the test. The purpose is to verify
# that Force can recover from this scenario.
class MainSequence(Sequence):
    def generate(self, **kargs):
        for _ in range(RandomUtils.random32(5, 10)):
            if self.getGlobalState("AppRegisterWidth") == 32:
                instr = RV32_G_map.pick(self.genThread)
            else:
                instr = RV_G_map.pick(self.genThread)
            self.genInstruction(instr)

        self.genInstruction("MRET##CALM", {"NoSkip": 1, "priv": 1})

        for _ in range(RandomUtils.random32(5, 10)):
            if self.getGlobalState("AppRegisterWidth") == 32:
                instr = RV32_G_map.pick(self.genThread)
            else:
                instr = RV_G_map.pick(self.genThread)
            self.genInstruction(instr)

        target_addr = self.genVA(Size=4, Align=4, Type="I")
        self.genInstruction("SRET##CALM", {"NoSkip": 1, "epc": target_addr, "priv": 0})


MainSequenceClass = MainSequence
GenThreadClass = GenThreadGPGPU
EnvClass = EnvGPGPU
